package com.mooc.action;

import javax.annotation.Resource;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.mooc.bean.MoocUser;
import com.mooc.service.IUserService;
import com.mooc.util.MyUtil;

/**
 * 用户操作
 * @author szspace
 */
@RestController
public class UserAction {
	
	@Resource
	private IUserService userService;

	/**
	 * 用户登录通过账号密码的方式
	 * @param moocUser
	 * @return
	 */
	@RequestMapping(value="/userLogin", method=RequestMethod.POST)
	public ModelAndView userLogin(MoocUser moocUser) {
		
		boolean loginFlag = false;
		// 调用 service 层获得登录判断结果
		loginFlag = userService.loginJudge(moocUser);
		
		ModelAndView mav = new ModelAndView();
		// 跳转至登录成功的页面
		if (loginFlag) {
			mav.setViewName("XXXXXXXXXXXX");
		}
		// 返回是否登录成功标志
		mav.addObject("loginFlag", loginFlag);
		return mav;
	}
	
	
	/**
	 * 获取手机验证码
	 * @param userPhone
	 * @return
	 */
	@RequestMapping(value="/getSecurityCode", method=RequestMethod.GET)
	public ResponseEntity<String> userLoginByCode(@RequestParam("userPhone") String userPhone) {
		
		String securityCode = null;
		HttpStatus httpStatus = null;
		// 验证手机号码是否唯一 
		if (!userService.judgePhoneUnique(userPhone)) {
			securityCode = MyUtil.getSecurityCode();
			httpStatus = HttpStatus.OK;
		} else {
			securityCode = "手机号码未注册";
			
			// 预计 会调用 ajax 的 error 回调函数 
			httpStatus = HttpStatus.NOT_EXTENDED;
		}
		
		return ResponseEntity.status(httpStatus).body(securityCode);
	}
	
	
	/**
	 * 判断手机号码的唯一性
	 * @param userPhone
	 * @return
	 */
	@RequestMapping(value="/judgePhoneUnique", method=RequestMethod.GET)
	public ResponseEntity<String> judgePhoneUnique(@RequestParam("userPhone") String userPhone){
		String msg = null;
		
		if (userService.judgePhoneUnique(userPhone)) { msg = "success"; }
		else { msg = "false"; }
		
		return ResponseEntity.status(HttpStatus.OK).body(msg);
	}
}
